package com.order.manager.controller.Online;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.OnlineInfo;
import com.order.manager.Model.OrderInfo;
import com.order.manager.Model.SenderInfo;
import com.order.manager.Model.ShopInfo;
import com.order.manager.Model.other.RestBean;
import com.order.manager.service.impl.*;
import com.order.manager.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/api/online")
public class OnlineController {
    @Resource
    OnlineInfoServiceImpl onlineInfoService;
    @Resource
    JwtUtil jwtUtil;

    @Resource
    ShopInfoServiceImpl shopInfoService;

    @Resource
    SenderInfoServiceImpl senderInfoService;

    @Resource
    OrderInfoServiceImpl orderInfoService;


    @RequestMapping("/chat/shop/{orderId}")
    public RestBean getChatWithShop(HttpServletRequest request, @PathVariable String orderId, String content) {
        OnlineInfo onlineInfo = new OnlineInfo();
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) return RestBean.failure(400, "没有订单信息");
        String uuid = jwtUtil.getJwtUsername(request);
        ShopInfo shopInfo = shopInfoService.getById(orderInfo.getShopId());
        if (shopInfo == null) return RestBean.failure(400, "不存在该商铺信息");
        String shopMasterId = shopInfo.getShopMasterId();
        onlineInfo.setSendId(uuid);
        onlineInfo.setReceiveId(shopMasterId);
        onlineInfo.setContent(content);
        onlineInfo.setSendTime(new Date());
        return onlineInfoService.save(onlineInfo) ? RestBean.success(onlineInfo) : RestBean.failure(500, "聊天失败");
    }
    @RequestMapping("/chat/user/{userId}")
    public RestBean getChatWithUser(HttpServletRequest request, @PathVariable String userId, String content) {
        OnlineInfo onlineInfo = new OnlineInfo();
        String uuid = jwtUtil.getJwtUsername(request);
        if (shopInfoService.count(new QueryWrapper<ShopInfo>()
                .eq("shop_master_id",uuid)
        )==0) {
            return RestBean.failure(400,"没有店铺信息");
        }
        ShopInfo shopMasterId = shopInfoService.getOne(new QueryWrapper<ShopInfo>()
                .eq("shop_master_id", uuid)
        );
        onlineInfo.setSendId(shopMasterId.getShopMasterId());
        onlineInfo.setReceiveId(userId);
        onlineInfo.setContent(content);
        onlineInfo.setSendTime(new Date());
        return onlineInfoService.save(onlineInfo) ? RestBean.success(onlineInfo) : RestBean.failure(500, "聊天失败");
    }

    @RequestMapping("/chat/sender/{senderId}")
    public RestBean getChatWithSenderId(HttpServletRequest request, @PathVariable String senderId, String content) {
        OnlineInfo onlineInfo = new OnlineInfo();
        String uuid = jwtUtil.getJwtUsername(request);
        SenderInfo senderInfo = senderInfoService.getById(senderId);
        if (senderInfo == null) return RestBean.failure(400, "不存在该配送员信息");
        String senderInfoUserId = senderInfo.getUserId();
        onlineInfo.setSendId(uuid);
        onlineInfo.setReceiveId(senderInfoUserId);
        onlineInfo.setContent(content);
        onlineInfo.setSendTime(new Date());
        return onlineInfoService.save(onlineInfo) ? RestBean.success(onlineInfo) : RestBean.failure(500, "聊天失败");
    }

    @RequestMapping("/all/chat/shop/{orderId}")
    public RestBean GetChatAllShop(@PathVariable String orderId, HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) return RestBean.failure(400, "没有该订单信息");
        ShopInfo shopInfo = shopInfoService.getById(orderInfo.getShopId());
        if (shopInfo == null) return RestBean.failure(400, "没有该店铺信息");
        List<OnlineInfo> onlineInfos1 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", uuid).eq("receive_id", shopInfo.getShopMasterId()));
        List<OnlineInfo> onlineInfos2 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", shopInfo.getShopMasterId()).eq("receive_id", uuid));
        List<OnlineInfo> onlineInfos = new ArrayList<>();
        onlineInfos.addAll(onlineInfos1);
        onlineInfos.addAll(onlineInfos2);
        Comparator<OnlineInfo> comparator = new Comparator<OnlineInfo>() {
            public int compare(OnlineInfo o1, OnlineInfo o2) {
                return o1.getSendTime().compareTo(o2.getSendTime());
            }
        };
// 使用比较器对 onlineInfos 列表进行排序
        Collections.sort(onlineInfos, comparator);
        onlineInfos.forEach(el->{
            if (el.getSendId().equals(uuid)){
                el.setContent("我："+el.getContent()+"            "+JSON.toJSONString(el.getSendTime()));
            }else{
                el.setContent("商家："+el.getContent()+"            "+ JSON.toJSONString(el.getSendTime()));
            }

        });

        return RestBean.success(onlineInfos);
    }
    @RequestMapping("/all/chat/user/{userId}")
    public RestBean GetChatAllUser(@PathVariable String userId, HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);

        if(shopInfoService.count(new QueryWrapper<ShopInfo>()
                .eq("shop_master_id",uuid)
        ) == 0){
            return RestBean.failure(400,"不存在店铺信息");
        }
        ShopInfo shopMasterId = shopInfoService.getOne(new QueryWrapper<ShopInfo>()
                .eq("shop_master_id", uuid)
        );

        List<OnlineInfo> onlineInfos1 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", userId).eq("receive_id", shopMasterId.getShopMasterId()));
        List<OnlineInfo> onlineInfos2 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", shopMasterId.getShopMasterId()).eq("receive_id", userId));
        List<OnlineInfo> onlineInfos = new ArrayList<>();
        onlineInfos.addAll(onlineInfos1);
        onlineInfos.addAll(onlineInfos2);
        Comparator<OnlineInfo> comparator = new Comparator<OnlineInfo>() {
            public int compare(OnlineInfo o1, OnlineInfo o2) {
                return o1.getSendTime().compareTo(o2.getSendTime());
            }
        };
// 使用比较器对 onlineInfos 列表进行排序
        Collections.sort(onlineInfos, comparator);
        onlineInfos.forEach(el->{
            if (el.getSendId().equals(userId)){
                el.setContent("客户："+el.getContent()+"            "+JSON.toJSONString(el.getSendTime()));
            }else{
                el.setContent("我："+el.getContent()+"            "+ JSON.toJSONString(el.getSendTime()));
            }

        });

        return RestBean.success(onlineInfos);
    }

    @RequestMapping("/all/chat/sender/{senderId}")
    public RestBean GetChatAllSender(@PathVariable String senderId, HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);
        SenderInfo senderInfo = senderInfoService.getById(senderId);
        if (senderInfo == null) return RestBean.failure(400, "没有该配送员信息");
        List<OnlineInfo> onlineInfos1 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", uuid).eq("receive_id", senderInfo.getUserId()));
        List<OnlineInfo> onlineInfos2 = onlineInfoService.list(new QueryWrapper<OnlineInfo>().eq("send_id", senderInfo.getUserId()).eq("receive_id", uuid));
        List<OnlineInfo> onlineInfos = new ArrayList<>();
        onlineInfos.addAll(onlineInfos1);
        onlineInfos.addAll(onlineInfos2);
        Comparator<OnlineInfo> comparator = new Comparator<OnlineInfo>() {
            public int compare(OnlineInfo o1, OnlineInfo o2) {
                return o1.getSendTime().compareTo(o2.getSendTime());
            }
        };
// 使用比较器对 onlineInfos 列表进行排序
        Collections.sort(onlineInfos, comparator);
        return RestBean.success(onlineInfos);
    }


}
